package com.base.component.app.push.apns;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;

import com.base.component.app.push.bo.PushBO;
import com.base.component.app.push.bo.PushIdBO;
import com.base.component.app.push.bo.PushListBO;
import com.base.component.app.push.core.PushHandler;
import com.eatthepath.pushy.apns.ApnsClient;
import com.eatthepath.pushy.apns.ApnsClientBuilder;
import com.eatthepath.pushy.apns.util.ApnsPayloadBuilder;
import com.eatthepath.pushy.apns.util.SimpleApnsPayloadBuilder;
import com.eatthepath.pushy.apns.util.SimpleApnsPushNotification;
import com.eatthepath.pushy.apns.util.TokenUtil;
import com.gitee.magic.core.exception.ApplicationException;
import com.gitee.magic.framework.base.constant.Config;

/**
 * 
 * @author start
 */
public abstract class ApnsConnectBase<P extends PushBO> implements PushHandler<P> {

	@Value("${packageName.ios}")
	private String packageName;

	@Value("${push.apns.p12.path}")
	private String p12path;
	@Value("${push.apns.p12.password}")
	private String p12password;

	private ApnsClient apnsClient;

	public void push(PushListBO list) {
		for (String token : list.getTokenIds()) {
			PushIdBO o=new PushIdBO();
			BeanUtils.copyProperties(list,o);
			o.setTokenId(token);
			push(o);
		}
	}

	public void push(PushIdBO o) {
		
		Map<String,Object> extras=new HashMap<>(1);
		extras.put("msg", o.getParams());
		
		ApnsPayloadBuilder payloadBuilder = new SimpleApnsPayloadBuilder();
		payloadBuilder.setAlertTitle(o.getTitle());
		payloadBuilder.setAlertBody(o.getBody());
		payloadBuilder.setContentAvailable(false);
		if(o.isSound()) {
			payloadBuilder.setSound("default");
		}else {
			payloadBuilder.setSound("");
		}
		for (Map.Entry<String, Object> map : extras.entrySet()) {
			payloadBuilder.addCustomProperty(map.getKey(), map.getValue());
		}
		payloadBuilder.setMutableContent(true);
		SimpleApnsPushNotification sapn = new SimpleApnsPushNotification(TokenUtil.sanitizeTokenString(o.getTokenId()),
				packageName, payloadBuilder.build());
		apnsClient().sendNotification(sapn);

//		PushNotificationFuture<SimpleApnsPushNotification, PushNotificationResponse<SimpleApnsPushNotification>> future = apnsClient()
//				.sendNotification(sapn);
//		PushNotificationResponse<SimpleApnsPushNotification> response;
//		try {
//			response = future.get();
//		} catch (InterruptedException e) {
//			throw new ApplicationException(e);
//		} catch (ExecutionException e) {
//			throw new ApplicationException(e);
//		}
//		if (response.isAccepted()) {
//			System.out.println("Push notification accepted by APNs gateway.");
//		} else {
//			System.out.println("Notification rejected by the APNs gateway: " + response.getRejectionReason());
//
//			response.getTokenInvalidationTimestamp().ifPresent(timestamp -> {
//				System.out.println("\t…and the token is invalid as of " + timestamp);
//			});
//		}
	}

	public ApnsClient apnsClient() {
		if (apnsClient == null) {
			try {
				ClassPathResource cpr = new ClassPathResource(p12path);
				apnsClient = new ApnsClientBuilder()
						.setApnsServer(Config.isSystemFlag() ? ApnsClientBuilder.PRODUCTION_APNS_HOST
								: ApnsClientBuilder.DEVELOPMENT_APNS_HOST)
						.setClientCredentials(cpr.getInputStream(), p12password).setConcurrentConnections(4).build();
			} catch (Exception e) {
				throw new ApplicationException(e);
			}
		}
		return apnsClient;
	}

}
